package com.ywy.chat.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.ywy.chat.ChatConstants;
import com.ywy.chat.service.ChatService;
import com.ywy.chat.vo.ChatMessage;
import com.ywy.chat.vo.ChatUser;
import com.ywy.shiro.AccountProfile;
import com.ywy.utils.RedisUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 群聊Service实现
 *
 * @author ywy
 * @date 2021/12/31 15:13
 */
@Service("chatService")
public class ChatServiceImpl implements ChatService {
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public ChatUser getCurrentUser() {
        // 获取登录用户消息
        AccountProfile profile = (AccountProfile) SecurityUtils.getSubject().getPrincipal();
        ChatUser user = new ChatUser();
        // 不为空说明用户已登录
        if (profile != null) {
            user.setId(profile.getId());
            user.setAvatar(profile.getAvatar());
            user.setUsername(profile.getUsername());
            user.setMine(true);
            user.setStatus(ChatUser.ONLINE_STATUS);
        } else {
            // 用户未登录，生成匿名用户
            user.setAvatar("/images/avatar.png");
            Integer userId = (Integer) SecurityUtils.getSubject().getSession().getAttribute("chatUserId");
            user.setId(userId != null ? userId : RandomUtil.randomInt());

            // 给匿名用户分配了一个随机id，保存在session中
            SecurityUtils.getSubject().getSession().setAttribute("chatUserId", user.getId());
            user.setUsername("匿名用户");
            user.setSign("never give up!");
            user.setStatus(ChatUser.ONLINE_STATUS);
        }

        return user;
    }

    @Override
    public void setGroupHistoryMsg(ChatMessage chatMessage) {
        // 保存群聊消息24小时
        redisUtil.lrpush(ChatConstants.GROUP_HISTORY_MSG_KEY, chatMessage, 24 * 60 * 60);
    }

    @Override
    public List<Object> getGroupHistoryMsg(int count) {
        long length = redisUtil.llen(ChatConstants.GROUP_HISTORY_MSG_KEY);
        // 只获取最近count条记录
        return redisUtil.lrange(ChatConstants.GROUP_HISTORY_MSG_KEY, length - count < 0 ? 0 : length - count, length);
    }

}
